package version1.part2.Client.rpcClient.Impl;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;
import version1.part1.common.message.RpcRequest;
import version1.part1.common.message.RpcResponse;
import version1.part2.Client.RpcClient;
import version1.part2.Client.netty.nettyinitalizer.NettyClientInitializer;

import java.io.IOException;

/**
 * @author Stone
 * @version 1.0.1
 * @date 2025/9/19
 */
public class NettyRpcClient implements RpcClient {

    private String host;
    private int port;
    private static final Bootstrap bootstrap;
    private static final EventLoopGroup eventLoopGroup;

    public NettyRpcClient(String host, int port) {
        this.host = host;
        this.port = port;
    }
    //netty客户端初始化
    static {
        bootstrap = new Bootstrap();
        eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                .handler(new NettyClientInitializer());
        //配置netty对消息的处理机制

    }

    @Override
    public RpcResponse sendRequest(RpcRequest request) throws IOException {

        //创建一个channelFuture对象，代表这一个操作事件，sync方法表示堵塞知道连接完成
        try {
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //表示一个连接的单位
            Channel channel = channelFuture.channel();
//            发送数据
            channel.writeAndFlush(request);
            //堵塞获取结果
            channel.closeFuture().sync();
            AttributeKey<RpcResponse> key = AttributeKey.valueOf("RpcResponse");
            RpcResponse response = channel.attr(key).get();

            System.out.println(response);
            return  response;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }
}
